package tasks.zhuanyeji.分布式任务调度;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class MySolution {
    public static void main(String[] args) {
        int[][] arr = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {6, 4}, {8, 7}};
        int minTime = new MySolution().getMinTime(9, arr);
        System.out.println(minTime);
    }

    public int getMinTime(int taskNum, int[][] relations) {
        List<List<Integer>> graphList = new ArrayList<>();
        for (int i = 0; i <= taskNum; i++) {
            graphList.add(new ArrayList<>());
        }

        int degree[] = new int[taskNum + 1];
        for (int[] relation : relations) {
            int d1 = relation[0];
            int d2 = relation[1];
            graphList.get(d2).add(d1);
            degree[d1]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i <= taskNum; i++) {
            if (degree[i] == 0) {
                queue.offer(i);
            }
        }


        int minutes = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Integer node = queue.poll();
                for (Integer next : graphList.get(node)) {
                    degree[next]--;
                    if (degree[next] == 0) {
                        queue.offer(next);
                    }
                }
            }
            minutes++;
        }
        return minutes;
    }
}
